<?php

/*
 * 2007-2012 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author PrestaShop SA <contact@prestashop.com>
 *  @copyright  2007-2012 PrestaShop SA
 *  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

class OrderControllerCore extends ParentOrderController {

    public $step;
    protected $_address;
    protected $id_address = null;

    /**
     * Initialize order controller
     * @see FrontController::init()
     */

    /**
     * Set default medias for this controller
     */
    public function setMedia() {
        parent::setMedia();
        $this->addJS(_THEME_JS_DIR_ . 'tools/statesManagement.js');
    }

    public function init() {
        global $orderTotal;

        parent::init();

        $this->step = (int) (Tools::getValue('step'));
        if (!$this->nbProducts)
            $this->step = -1;

        // If some products have disappear
        if (!$this->context->cart->checkQuantities()) {
            $this->step = 0;
            $this->errors[] = Tools::displayError('An item in your cart is no longer available in this quantity, you cannot proceed with your order.');
        }

        // Check minimal amount
        $currency = Currency::getCurrency((int) $this->context->cart->id_currency);

        $orderTotal = $this->context->cart->getOrderTotal();
        $minimal_purchase = Tools::convertPrice((float) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
        if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase && $this->step != -1) {
            $this->step = 0;
            $this->errors[] = sprintf(
                    Tools::displayError('A minimum purchase total of %s is required in order to validate your order.'), Tools::displayPrice($minimal_purchase, $currency)
            );
        }
        if (!$this->context->customer->isLogged(true) && in_array($this->step, array(1, 2, 3))) {
            $back_url = $this->context->link->getPageLink('order', true, (int) $this->context->language->id, array('step' => $this->step, 'multi-shipping' => (int) Tools::getValue('multi-shipping')));
            $params = array('multi-shipping' => (int) Tools::getValue('multi-shipping'), 'display_guest_checkout' => (int) Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'back' => $back_url);
            Tools::redirect($this->context->link->getPageLink('authentication', true, (int) $this->context->language->id, $params));
        }

        if (Tools::getValue('multi-shipping') == 1)
            $this->context->smarty->assign('multi_shipping', true);
        else
            $this->context->smarty->assign('multi_shipping', false);

        if ($this->context->customer->id)
            $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
        else
            $this->context->smarty->assign('address_list', array());
    }

    public function postProcess() {
        // Update carrier selected on preProccess in order to fix a bug of
        // block cart when it's hooked on leftcolumn
        if (!Validate::isLoadedObject($this->_address) && Validate::isLoadedObject($this->context->customer)) {
            $_POST['firstname'] = $this->context->customer->firstname;
            $_POST['lastname'] = $this->context->customer->lastname;
            //$_POST['company'] = $this->context->customer->company;
        }
        if (Tools::getValue('id_address')) {
            $this->id_address = Tools::getValue('id_address', 0);
            $this->_address = new Address($this->id_address);
        }
        if (Tools::isSubmit('submitAddress'))
            $this->processSubmitAddress();
        if (Tools::isSubmit('SubmitLogin'))
            $this->processSubmitLogin();
//        if ($this->step == 3 && Tools::isSubmit('processCarrier'))
//            $this->processCarrier();
    }

    protected function assignCountries() {
        // Get selected country
        if (Tools::isSubmit('id_country') && !is_null(Tools::getValue('id_country')) && is_numeric(Tools::getValue('id_country')))
            $selected_country = (int) Tools::getValue('id_country');
        else if (isset($this->_address) && isset($this->_address->id_country) && !empty($this->_address->id_country) && is_numeric($this->_address->id_country))
            $selected_country = (int) $this->_address->id_country;
        else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $array = preg_split('/,|-/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            if (!Validate::isLanguageIsoCode($array[0]) || !($selected_country = Country::getByIso($array[0])))
                $selected_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
        } else
            $selected_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');

        // Generate countries list
        if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES'))
            $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
        else
            $countries = Country::getCountries($this->context->language->id, true);

        // @todo use helper
        $list = '';
        foreach ($countries as $country) {
            $selected = ($country['id_country'] == $selected_country) ? 'selected="selected"' : '';
            $list .= '<option value="' . (int) $country['id_country'] . '" ' . $selected . '>' . htmlentities($country['name'], ENT_COMPAT, 'UTF-8') . '</option>';
        }

        // Assign vars
        $this->context->smarty->assign(array(
            'countries_list' => $list,
            'countries' => $countries,
        ));
    }

    /**
     * Assign template vars related to page content
     * @see FrontController::initContent()
     */
    public function initContent() {
        global $isVirtualCart;
        $this->context->smarty->assign('genders', Gender::getGenders());
        parent::initContent();

        if (Tools::isSubmit('ajax') && Tools::getValue('method') == 'updateExtraCarrier') {
            // Change virtualy the currents delivery options
            $delivery_option = $this->context->cart->getDeliveryOption();
            $delivery_option[(int) Tools::getValue('id_address')] = Tools::getValue('id_delivery_option');
            $this->context->cart->setDeliveryOption($delivery_option);
            $this->context->cart->save();
            $return = array(
                'content' => Hook::exec(
                        'displayCarrierList', array(
                    'address' => new Address((int) Tools::getValue('id_address'))
                        )
                )
            );
            die(Tools::jsonEncode($return));
        }

        if ($this->nbProducts)
            $this->context->smarty->assign('virtual_cart', $isVirtualCart);

        // 4 steps to the order
        switch ((int) $this->step) {
            case -1;
                $check_logged = $this->context->customer->isLogged(true);
                $this->context->smarty->assign('check_logged', $check_logged);
                $this->context->smarty->assign('empty', 1);
                $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                break;

            case 1:

                //$this->_assignAddress();
                $this->processAddressFormat();
                $customer = $this->context->customer;

                $addresses = $customer->getAddresses($this->context->language->id);
                $this->assignCountries();

                $firt_address = null;
                foreach ($addresses as $address) {
                    $this->id_address = $address['id_address'];
                    $firt_address = $address;
                    break;
                }
                $id_country = is_null($firt_address) ? 0 : $firt_address['id_country'];

                $dlv_adr_fields = AddressFormat::getOrderedAddressFields($id_country, true, true);
                $this->_address = new Address($this->id_address);
                $this->context->smarty->assign('ordered_adr_fields', $dlv_adr_fields);
                $this->context->smarty->assign('address', $firt_address);
                $this->context->smarty->assign('id_address', $this->id_address);
                $this->context->smarty->assign('token', Tools::getToken(false));
                $this->context->smarty->assign(array(
                    'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'),
                    'ajaxurl' => _MODULE_DIR_,
                    'errors' => $this->errors,
                ));

                $this->assignVatNumber();
                if (Tools::getValue('multi-shipping') == 1) {

                    $this->_assignSummaryInformations();
                    $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
                    $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping.tpl');
                } else
                    $this->context->smarty->assign('theme_dir', _PS_THEME_DIR_);
                $this->setTemplate(_PS_THEME_DIR_ . 'order-my-address.tpl');

                break;

            case 2:
                
                $this->_assignAddress();

                $this->processAddressFormat();
                $customer = $this->context->customer;
                
                $addresses = $customer->getAddresses($this->context->language->id);
                $this->assignCountries();
                
                $firt_address = null;
                $count = 0;
                foreach ($addresses as $address) {
                    $this->id_address = $address['id_address'];
                    $firt_address = $address;
                    $count = $count + 1;
                }
                if ($count == 1)
                    $this->id_address = null;
                $id_country = is_null($firt_address) ? 0 : $firt_address['id_country'];

                $dlv_adr_fields = AddressFormat::getOrderedAddressFields($id_country, true, true);
                $this->context->smarty->assign('ordered_adr_fields', $dlv_adr_fields);
                $this->context->smarty->assign('address', $firt_address);
                $this->context->smarty->assign('id_address', $this->id_address);
                $this->context->smarty->assign('token', Tools::getToken(false));
                $this->context->smarty->assign(array(
                    'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'),
                    'ajaxurl' => _MODULE_DIR_,
                    'errors' => $this->errors,
                ));
                $this->assignVatNumber();
//                $this->autoStep();
                //$this->_assignCarrier();
                $this->setTemplate(_PS_THEME_DIR_ . 'order-billing-address.tpl');
                break;

            case 3:

                // Check that the conditions (so active) were accepted by the customer
//				$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
//
//				if (Configuration::get('PS_CONDITIONS') && (!Validate::isBool($cgv) || $cgv == false))
//					Tools::redirect('index.php?controller=order&step=2');
                Context::getContext()->cookie->check_cgv = true;

                // Check the delivery option is setted
//				if (!$this->context->cart->isVirtualCart())
//				{
//					if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier)
//						Tools::redirect('index.php?controller=order&step=2');
//					elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier)
//					{
//						foreach (Tools::getValue('delivery_option') as $delivery_option)
//							if (empty($delivery_option))
//								Tools::redirect('index.php?controller=order&step=2');
//					}
//				}

//                $this->autoStep();

                // Bypass payment step if total is 0
                if (($id_order = $this->_checkFreeOrder()) && $id_order) {
                    if ($this->context->customer->is_guest) {
                        $order = new Order((int) $id_order);
                        $email = $this->context->customer->email;
                        $this->context->customer->mylogout(); // If guest we clear the cookie for security reason
                        Tools::redirect('index.php?controller=guest-tracking&id_order=' . urlencode($order->reference) . '&email=' . urlencode($email));
                    } else
                        Tools::redirect('index.php?controller=history');
                }
                $this->_assignPayment();
                // assign some informations to display cart
                $this->_assignSummaryInformations();
                $this->setTemplate(_PS_THEME_DIR_ . 'order-payment.tpl');
                break;

            default:
                $this->_assignSummaryInformations();
                $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                break;
        }

        $this->context->smarty->assign(array(
            'currencySign' => $this->context->currency->sign,
            'currencyRate' => $this->context->currency->conversion_rate,
            'currencyFormat' => $this->context->currency->format,
            'currencyBlank' => $this->context->currency->blank,
        ));
    }

//    process login
    protected function processSubmitLogin() {
        Hook::exec('actionBeforeAuthentication');
        $passwd = trim(Tools::getValue('passwd'));
        $email = trim(Tools::getValue('email'));
        if (empty($email))
            $this->errors[] = Tools::displayError('E-mail address required');
        elseif (!Validate::isEmail($email))
            $this->errors[] = Tools::displayError('Invalid e-mail address'); elseif (empty($passwd))
            $this->errors[] = Tools::displayError('Password is required'); elseif (!Validate::isPasswd($passwd))
            $this->errors[] = Tools::displayError('Invalid password'); else {
            $customer = new Customer();
            $authentication = $customer->getByEmail(trim($email), trim($passwd));
            if (!$authentication || !$customer->id)
                $this->errors[] = Tools::displayError('Authentication failed');
            else {
                $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                $this->context->cookie->id_customer = (int) ($customer->id);
                $this->context->cookie->customer_lastname = $customer->lastname;
                $this->context->cookie->customer_firstname = $customer->firstname;
                $this->context->cookie->logged = 1;
                $customer->logged = 1;
                $this->context->cookie->is_guest = $customer->isGuest();
                $this->context->cookie->passwd = $customer->passwd;
                $this->context->cookie->email = $customer->email;

                // Add customer to the context
                $this->context->customer = $customer;

                if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0))
                    $this->context->cookie->id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id);

                // Update cart address
                $this->context->cart->id = $this->context->cookie->id_cart;
                $this->context->cart->setDeliveryOption(null);
                $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) ($customer->id));

                $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) ($customer->id));
                $this->context->cart->secure_key = $customer->secure_key;
                $this->context->cart->update();
                $this->context->cart->autosetProductAddress();

                Hook::exec('actionAuthentication');

                // Login information have changed, so we check if the cart rules still apply
                CartRule::autoRemoveFromCart($this->context);
                CartRule::autoAddToCart($this->context);

                if (!$this->ajax) {
                    if ($back = Tools::getValue('back'))
                        Tools::redirect(html_entity_decode($back));
                    Tools::redirect('index.php?controller=order&step=1');
                }
            }
        }
        if ($this->ajax) {
            $return = array(
                'hasError' => !empty($this->errors),
                'errors' => $this->errors,
                'token' => Tools::getToken(false)
            );
            die(Tools::jsonEncode($return));
        } else
            $this->context->smarty->assign('authentification_error', $this->errors);
    }

    protected function processAddressFormat() {
        
        $addressDelivery = new Address((int) $this->context->cart->id_address_delivery);
        $addressInvoice = new Address((int) $this->context->cart->id_address_invoice);

        $invoiceAddressFields = AddressFormat::getOrderedAddressFields($addressInvoice->id_country, false, true);
        $deliveryAddressFields = AddressFormat::getOrderedAddressFields($addressDelivery->id_country, false, true);

        $this->context->smarty->assign(array(
            'inv_adr_fields' => $invoiceAddressFields,
            'dlv_adr_fields' => $deliveryAddressFields));
    }

    /**
     * Order process controller
     */
    public function autoStep() {
        global $isVirtualCart;

//        if ($this->step >= 2 && (!$this->context->cart->id_address_delivery || !$this->context->cart->id_address_invoice))
//            Tools::redirect('index.php?controller=order&step=1');

        if ($this->step > 2 && !$isVirtualCart && count($this->context->cart->getDeliveryOptionList()) == 0)
            Tools::redirect('index.php?controller=order&step=2');

        $delivery = new Address((int) $this->context->cart->id_address_delivery);
        $invoice = new Address((int) $this->context->cart->id_address_invoice);

        if ($delivery->deleted || $invoice->deleted) {
            if ($delivery->deleted)
                unset($this->context->cart->id_address_delivery);
            if ($invoice->deleted)
                unset($this->context->cart->id_address_invoice);
            Tools::redirect('index.php?controller=order&step=1');
        }
    }

    /**
     * Manage address
     */
    public function processAddress() {
        if (!Tools::getValue('multi-shipping'))
            $this->context->cart->setNoMultishipping();

        if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery'))
                || (Tools::isSubmit('same') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice')))
        )
            $this->errors[] = Tools::displayError('Invalid address');
        else {
            // Add checking for all addresses
            $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers();
            if (count($address_without_carriers)) {
                if (count($address_without_carriers) > 1)
                    $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.'));
                elseif ($this->context->cart->isMultiAddressDelivery())
                    $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.')); else
                    $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.'));
            } else {
                $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
                $this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');

                CartRule::autoRemoveFromCart($this->context);
                CartRule::autoAddToCart($this->context);

                if (!$this->context->cart->update())
                    $this->errors[] = Tools::displayError('An error occurred while updating your cart.');

                if (!$this->context->cart->isMultiAddressDelivery())
                    $this->context->cart->setNoMultishipping(); // If there is only one delivery address, set each delivery address lines with the main delivery address

                if (Tools::isSubmit('message'))
                    $this->_updateMessage(Tools::getValue('message'));
            }
        }

        if ($this->errors) {
            if (Tools::getValue('ajax'))
                die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
            $this->step = 1;
        }

        if ($this->ajax)
            die(true);
    }

    /**
     * Carrier step
     */
    protected function processCarrier() {
        global $orderTotal;
        parent::_processCarrier();

        if (count($this->errors)) {
            $this->context->smarty->assign('errors', $this->errors);
            $this->_assignCarrier();
            $this->step = 2;
            $this->displayContent();
            include(dirname(__FILE__) . '/../footer.php');
            exit;
        }
        $orderTotal = $this->context->cart->getOrderTotal();
    }

    /**
     * Address step
     */
    protected function _assignAddress() {
        parent::_assignAddress();

        if (Tools::getValue('multi-shipping'))
            $this->context->cart->autosetProductAddress();

        $this->context->smarty->assign('cart', $this->context->cart);
    }

    /**
     * Carrier step
     */
    protected function _assignCarrier() {
        if (!isset($this->context->customer->id))
            die(Tools::displayError('Fatal error: No customer'));
        // Assign carrier
        parent::_assignCarrier();
        // Assign wrapping and TOS
        $this->_assignWrappingAndTOS();

        // If a rule offer free-shipping, force hidding shipping prices
        $free_shipping = false;
        foreach ($this->context->cart->getCartRules() as $rule)
            if ($rule['free_shipping']) {
                $free_shipping = true;
                break;
            }

        $this->context->smarty->assign(
                array(
                    'free_shipping' => $free_shipping,
                    'is_guest' => (isset($this->context->customer->is_guest) ? $this->context->customer->is_guest : 0)
        ));
    }

    /**
     * Payment step
     */
    protected function _assignPayment() {
        global $orderTotal;

        // Redirect instead of displaying payment modules if any module are grefted on
        Hook::exec('displayBeforePayment', array('module' => 'order.php?step=3'));

        /* We may need to display an order summary */
        $this->context->smarty->assign($this->context->cart->getSummaryDetails());
        $this->context->smarty->assign(array(
            'total_price' => (float) ($orderTotal),
            'taxes_enabled' => (int) (Configuration::get('PS_TAX'))
        ));
        $this->context->cart->checkedTOS = '1';

        parent::_assignPayment();
    }

    protected function processSubmitAddress() {
        
        $address = new Address();
        $this->errors = $address->validateController();
        $address->id_customer = (int) $this->context->customer->id;

        // Check page token
        if ($this->context->customer->isLogged() && !$this->isTokenValid())
            $this->errors[] = Tools::displayError('Invalid token');

        // Check phone
        if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
            $this->errors[] = Tools::displayError('You must register at least one phone number');
        if ($address->id_country) {
            // Check country
            if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country))
                throw new PrestaShopException('Country cannot be loaded with address->id_country');

            if ((int) $country->contains_states && !(int) $address->id_state)
                $this->errors[] = Tools::displayError('This country requires a state selection.');

            // US customer: normalize the address
            if ($address->id_country == Country::getByIso('US')) {
                include_once(_PS_TAASC_PATH_ . 'AddressStandardizationSolution.php');
                $normalize = new AddressStandardizationSolution;
                //$address->address1 = $normalize->AddressLineStandardization($address->address1);
                //$address->address2 = $normalize->AddressLineStandardization($address->address2);
            }

            // Check country zip code
            $zip_code_format = $country->zip_code_format;
            if ($country->need_zip_code) {
                if (($postcode = Tools::getValue('postcode')) && $zip_code_format) {
                    if (!$country->checkZipCode($postcode))
                        $this->errors[] = sprintf(
                                Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)))
                        );
                } else if ($zip_code_format)
                    $this->errors[] = Tools::displayError('Zip/Postal code is required.');
                else if ($postcode && !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode))
                    $this->errors[] = sprintf(
                            Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)))
                    );
            }

            // Check country DNI
            if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
                $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
            else if (!$country->isNeedDni())
                $address->dni = null;
        }
        // Check if the alias exists
        if (!$this->context->customer->is_guest && !empty($_POST['alias'])
                && (int) $this->context->customer->id > 0
                && Db::getInstance()->getValue('
				SELECT count(*)
				FROM ' . _DB_PREFIX_ . 'address
				WHERE `alias` = \'' . pSql($_POST['alias']) . '\'
				AND id_address != ' . (int) Tools::getValue('id_address') . '
				AND id_customer = ' . (int) $this->context->customer->id . '
				AND deleted = 0') > 0
        )
            $this->errors[] = sprintf(Tools::displayError('The alias "%s" is already used, please chose another one.'), Tools::safeOutput($_POST['alias']));

        // Check the requires fields which are settings in the BO
        $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());

        // Don't continue this process if we have errors !
        if ($this->errors && !$this->ajax) {


            return;
        }
        // If we edit this address, delete old address and create a new one
        if (Validate::isLoadedObject($this->_address)) {

            if (Validate::isLoadedObject($country) && !$country->contains_states)
                $address->id_state = 0;
            $address_old = $this->_address;

            if (Customer::customerHasAddress($this->context->customer->id, (int) $address_old->id)) {
                if ($address_old->isUsed())
                    $address_old->delete();
                else {
                    $address->id = (int) ($address_old->id);
                    $address->date_add = $address_old->date_add;
                }
            }
        }

        // Save address
        if ($result = $address->save()) {
            // Update id address of the current cart if necessary
            if (isset($address_old) && $address_old->isUsed())
                $this->context->cart->updateAddressId($address_old->id, $address->id);
            else // Update cart address
                $this->context->cart->autosetProductAddress();

            if ($this->ajax) {
                $return = array(
                    'hasError' => (bool) $this->errors,
                    'errors' => $this->errors,
                    'id_address_delivery' => $this->context->cart->id_address_delivery,
                    'id_address_invoice' => $this->context->cart->id_address_invoice
                );
                die(Tools::jsonEncode($return));
            }

            // Redirect to old page or current page
            if (Tools::getValue('step') == 2) {
                $this->context->smarty->assign('txtMessage', Tools::getValue('txtMessage'));
                $this->context->cookie->__set('tmpDeliveryDate',Tools::getValue('datepicker'));
                //update Message
                $this->_updateMessageFromTo(Tools::getValue('txtMessage'),Tools::getValue('txtFrom'),Tools::getValue('txtTo'));
            }
            if ($back = Tools::getValue('back')) {
                $mod = Tools::getValue('mod');
                Tools::redirect('index.php?controller=' . $back . ($mod ? '&back=' . $mod : ''));
            } else if (Tools::getValue('step')) {
                Tools::redirect('index.php?controller=order&step=' . (Tools::getValue('step') + 1));
            }
        }
        $this->errors[] = Tools::displayError('An error occurred while updating your address.');
    }

    protected function assignVatNumber() {
        $vat_number_exists = file_exists(_PS_MODULE_DIR_ . 'vatnumber/vatnumber.php');
        $vat_number_management = Configuration::get('VATNUMBER_MANAGEMENT');
        if ($vat_number_management && $vat_number_exists)
            include_once(_PS_MODULE_DIR_ . 'vatnumber/vatnumber.php');

        if ($vat_number_management && $vat_number_exists && VatNumber::isApplicable(Configuration::get('PS_COUNTRY_DEFAULT')))
            $vat_display = 2;
        else if ($vat_number_management)
            $vat_display = 1;
        else
            $vat_display = 0;

        $this->context->smarty->assign(array(
            'vatnumber_ajax_call' => file_exists(_PS_MODULE_DIR_ . 'vatnumber/ajax.php'),
            'vat_display' => $vat_display,
        ));
    }

}

